#include <stdio.h>
#include <string>
#include <vector>

#include "ClientBootstrap.h"
#include "Log.h"

using namespace dsth;
using std::vector;
using std::string;

class EchoClient {
public:
    EchoClient(EventLoop* loop, const InetSocketAddress& addr, const char* name)
        :client_(loop, addr, name) {
            client_.SetOnConnection(std::make_pair(this, &EchoClient::OnConnect));
            client_.SetOnMessage(std::make_pair(this, &EchoClient::OnMessage));
    }

    ~EchoClient() {}
    void OnConnect(Connection* conn) {
        std::string str("hello, world");
        conn->Send(str.c_str(), str.length());
        printf("%s send message %s to server.\n", client_.GetName(), str.c_str());
    }
    void OnMessage(Connection* conn, ChannelBuffer* buf, Timestamp time) {
        string msg(buf->FetchAsString());
        printf("Connection %d: RECV:%s SIZE:%d TIME:%s.\n", conn->GetId(),
            msg.c_str(), msg.size(), time.ToFomattedString().c_str());
        //conn->Send(msg.c_str(), msg.length());
    }

    void OnClose(Connection* conn) {
        //conn
    }

    void Run() {
        client_.Connect();
    }
private:
    ClientBootstrap client_;
};


int main(int argc, char** argv) {
#ifdef IS_WINDOWS
    WSADATA wsaData;
    int err = WSAStartup( MAKEWORD(2,2), &wsaData );
    if( err != NO_ERROR )
        printf("Error at WSAStartup\n");
#endif
        
    NewLogger("./echo_client.log", Logger::E_TRACE);
    EventLoop loop;
    InetSocketAddress addr("127.0.0.1", 2012);

    int client_count = 10;
    if (argc > 1) client_count = atoi(argv[1]);

    vector<EchoClient*> client_list;
    client_list.reserve(client_count);
    for (int i = 0; i < client_count; ++i) {
        char buf[32];
        snprintf(buf, sizeof buf, "Client%d", i);
        client_list.push_back(new EchoClient(&loop, addr, buf));
        client_list[i]->Run();
    }
    loop.Loop();
    while (!client_list.empty()) {
        delete client_list.back();
        client_list.pop_back();
    }

#ifdef IS_WINDOWS
    WSACleanup();
#endif
    return 0;
}
